package controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;

import data.Data;

@SuppressWarnings("serial")
public class TopicServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("utf-8");
		
		resp.setHeader( "Cache-Control", "public, max-age=86400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		String path = ((HttpServletRequest)req).getRequestURI();
		
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	
        	resp.getWriter().println("Bad request : "+req.getRequestURI());
        	resp.getWriter().close();
        	return ;
        	
        }

		// skip one token /sites/gooogle.com (remove sites)
		st.nextToken();
		String name = st.nextToken();
		name = URLDecoder.decode(name,"UTF-8").trim();
		
		DBCollection coll = Data.data("domain");

		DBCursor domain = coll.find(new BasicDBObject("lKeyword",name)).limit(30);
	
		if(domain != null && domain.size() > 0)
		{
			req.setAttribute("domain", domain);
			req.setAttribute("name", name);
			try {
				req.getRequestDispatcher("/topic.jsp").forward(req, resp);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
		else
		{
			DBCursor domains = coll.find(new BasicDBObject("lpKeyword",name)).limit(30);
			if(domains != null)
			{
				req.setAttribute("domain", domains);
				req.setAttribute("name", name);
				try {
					req.getRequestDispatcher("/topic.jsp").forward(req, resp);
				} catch (ServletException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}

}
